package com.yesep.learn.design.structural.flyweight;

import java.util.*;

public class MediaPlayerFactory {
    public static final String[] VIDEO_FILE_TYPE = new String[]{"mp4", "avi"};
    private final Map<String, IMediaPlayerFlyweight> mediaPlayers = new HashMap<>();

    public IMediaPlayerFlyweight getPlayer(String fileName) {
        IMediaPlayerFlyweight player = mediaPlayers.get(fileName);
        if (player == null) {
            player = getMediaPlayerFlyweight(fileName);
            mediaPlayers.put(fileName, player);
        }
        return player;
    }

    private IMediaPlayerFlyweight getMediaPlayerFlyweight(String fileName) {
        return isVideoFile(fileName) ? new VideoPlayerFlyweight(fileName) : new AudioPlayerFlyweight(fileName);
    }

    private boolean isVideoFile(String fileName) {
        Optional<String> opt = Arrays.stream(VIDEO_FILE_TYPE).filter(fileName::endsWith).findFirst();
        return opt.isPresent();
    }
}